package com.bs.bszhsq.controller;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bs.bszhsq.config.AuthAccess;
import com.bs.bszhsq.entity.*;
import com.bs.bszhsq.exception.ServiceException;
import com.bs.bszhsq.service.ICarportService;
import com.bs.bszhsq.service.IUsersService;
import com.bs.bszhsq.utils.MessageType;
import com.bs.bszhsq.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/echarts")
@Api(tags = "图表数据接口")
public class EchartsController {

    @Resource
    private IUsersService usersService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ICarportService carportService;


    @GetMapping
    @ApiOperation(value = "查询近7天用户量")
    public R getNumbers(){
        //先获取近七天的日期
        List<String> sevenDate = getSevenDate();
        //查询近七天的数据量  sql语句在后面
        List<Echarts>  articleList = usersService.selectWeekLookCount(sevenDate);
        //创建一个新集合  用来存放最终的数据
        List<Echarts> list = new ArrayList<>();
        //遍历七天的日期
        for(int i = 0; i < sevenDate.size(); i++){
            Echarts echartsEntity = new Echarts();
            echartsEntity.setTime(sevenDate.get(i));
            boolean b = false;
            //遍历获取到的数据
            for(int y =- 0; y < articleList.size(); y++){
                //用来判断某一天是否有数据 如果有就存到list中
                if (sevenDate.get(i).equals(articleList.get(y).getTime())){
                        echartsEntity.setNum(articleList.get(y).getNum());
                    list.add(echartsEntity);
                    b = true;
                    break;
                }
            }
            //如果没有 就设置num为0，再存放到list中
            if(!b){
                    echartsEntity.setNum("0");
                list.add(echartsEntity);
            }
        }
        return R.success(list);
    }
    @GetMapping("/role")
    @ApiOperation(value = "角色分布图")
    public R getRoles(){
        List<EchartsRoles> list = usersService.getRoles();
        return R.success(list);
    }

    @GetMapping("/echartsCar")
    @ApiOperation(value = "车位类型预定柱状图")
    public R getEchartsCar(){
       List<EchartsCarNum> list=carportService.getEchartsCar();
        list.stream().forEach(echartsCarNum -> {
            if (echartsCarNum.getName().equals(MessageType.CAR_COMMON.getCode())){
                echartsCarNum.setName(MessageType.CAR_COMMON.getName());
            }else if (echartsCarNum.getName().equals(MessageType.CAR_VIP.getCode())){
                echartsCarNum.setName(MessageType.CAR_VIP.getName());
            }else if (echartsCarNum.getName().equals(MessageType.CAR_GRAND.getCode())){
                echartsCarNum.setName(MessageType.CAR_GRAND.getName());
            }else if (echartsCarNum.getName().equals(MessageType.CAR_FREE.getCode())){
                echartsCarNum.setName(MessageType.CAR_FREE.getName());
            }
        });
        return R.success(list);
    }



    @GetMapping("/car")
    @ApiOperation(value = "车位分布图")
    public R getCars(){
     List<EchartsCarNum> list=carportService.getCars();
     list.stream().forEach(echartsCarNum -> {
         if (echartsCarNum.getName().equals(MessageType.CAR_COMMON.getCode())){
             echartsCarNum.setName(MessageType.CAR_COMMON.getName());
         }else if (echartsCarNum.getName().equals(MessageType.CAR_VIP.getCode())){
             echartsCarNum.setName(MessageType.CAR_VIP.getName());
         }else if (echartsCarNum.getName().equals(MessageType.CAR_GRAND.getCode())){
             echartsCarNum.setName(MessageType.CAR_GRAND.getName());
         }else if (echartsCarNum.getName().equals(MessageType.CAR_FREE.getCode())){
             echartsCarNum.setName(MessageType.CAR_FREE.getName());
         }
     });
     return R.success(list);
    }



    @GetMapping("/number")
    @ApiOperation(value = "后管首页数据统计")
    public R getNum(){
        EchartsData echartsData=new EchartsData();
        //总数
        int sum = usersService.count();
        //
        LambdaQueryWrapper<Users> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Users::getRole, MessageType.ROLE_ADMIN.getName());
        int roleNum = usersService.count(lqw);
        LambdaQueryWrapper<Users> lqw2=new LambdaQueryWrapper<>();
        lqw2.eq(Users::getRole,MessageType.ROLE_USER.getName());
        int userNum = usersService.count(lqw2);
        Integer scholar;
        try {
            String s = stringRedisTemplate.opsForValue().get(MessageType.LOGIN_NUM.getName());
            if (StrUtil.isBlank(s)){
              scholar=0;
            }else {
                scholar = Integer.valueOf(s);
            }
            echartsData.setRoleNum(roleNum);
            echartsData.setScholar(scholar);
            echartsData.setUserNum(userNum);
            echartsData.setSum(sum);
        } catch (NumberFormatException e) {
            throw new ServiceException("500","服务出小差了~");
        }
        return R.success(echartsData);
    }

    @GetMapping("/carNumber")
    @ApiOperation("社区车位信息统计")
    public R getCarNum(){

        EchartsCar echartsCar=new EchartsCar();
        //总数
        int sum = carportService.count();
        LambdaQueryWrapper<Carport> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Carport::getStatus,Integer.valueOf(MessageType.CART_TBD.getCode()))
        .or()
        .eq(Carport::getStatus,Integer.valueOf(MessageType.CART_NORESERVE.getCode()));
        //剩余车位
        int SurplusNum = carportService.count(lqw);
        lqw.clear();
        lqw.eq(Carport::getStatus,Integer.valueOf(MessageType.CART_ISRESERVE.getCode()));
        //已预定
        int IsReserve = carportService.count(lqw);
        lqw.clear();
        lqw.eq(Carport::getStatus,Integer.valueOf(MessageType.CART_NORESERVE.getCode()));
        //可预定
        int NoReserve = carportService.count(lqw);
        lqw.clear();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        String userId = JWT.decode(token).getAudience().get(0);
        Users users = usersService.getById(userId);
        lqw.eq(Carport::getStatus,Integer.valueOf(MessageType.CART_ISRESERVE.getCode()))
                .eq(Carport::getUserId,users.getId());
        //我的车位
        int count = carportService.count(lqw);
        echartsCar.setMyCar(count);
        echartsCar.setSum(sum);
        echartsCar.setIsReserve(IsReserve);
        echartsCar.setNoReserve(NoReserve);
        echartsCar.setSurplusNum(SurplusNum);
        return R.success(echartsCar);
    }





    public static List<String> getSevenDate() {
            List<String> dateList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        for (int i = 0; i < 7; i++) {
                Date date = DateUtils.addDays(new Date(), -i);
            String formatDate = sdf.format(date);
            dateList.add(formatDate);
        }
        return dateList;
    }



}
